﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;


namespace Utils.ModuleCoroutine
{
    /// <summary>
    /// 模组 | 协程管理
    /// </summary>
    public class ModuleCoroutine
    {
        /// <summary>
        /// 
        /// </summary>
        public ModuleCoroutine()
        {
            CoroutineLib = new Dictionary<string, Coroutine>();
        }


        /// <summary>
        /// 缓存 | 协程目录
        /// </summary>
        /// <remarks>
        /// <br/>string：UserID 
        /// <br/>Coroutinue：Unity COR
        /// </remarks>
        public Dictionary<string, Coroutine> CoroutineLib { get; private set; } 


        /// <summary>
        /// 获取 | UserID 关联协程项
        /// </summary>
        public bool TryGet(string userID, out Coroutine output)
        {
            bool isGet = CoroutineLib.TryGetValue(userID, out output);
            if (!isGet)
            {
                output = null;
                return false;
            }

            return true;
        }

        /// <summary>
        /// 记录 | 校验与更新协程
        /// </summary>
        public void DoRecord(string userID, Coroutine newCOR)
        {
            if (CoroutineLib.ContainsKey(userID))
            {
                TimeCoroutine.Stop(CoroutineLib[userID]);
                CoroutineLib[userID] = newCOR;
                return;
            }

            CoroutineLib.Add(userID, newCOR);
        }


        /// <summary>
        /// 释放 | 特定协程
        /// </summary>
        /// <param name="userID"></param>
        public void DoDisposed(string userID)
        {
            bool isGet = this.TryGet(userID, out Coroutine output);
            if (isGet)
            {
                TimeCoroutine.Stop(output);
            }
        }

        /// <summary>
        /// 释放 | 所有协程
        /// </summary>
        public void DoDisposed()
        {
            CoroutineLib.ToList().ForEach(cor =>
            {
                TimeCoroutine.Stop(cor.Value);
            });

            CoroutineLib.Clear();
        }
    }
}
